import os
import json
from pathlib import Path
from .config import config, ROOT_DIR

# 从配置中获取存储路径
STORAGE_CONFIG = config.get('storage', {})
AUTH_DIR = ROOT_DIR / STORAGE_CONFIG.get('auth_dir', 'auto')
AUTH_FILE_PATH = AUTH_DIR / STORAGE_CONFIG.get('auth_file', 'auto.json')

# 创建auth目录（如果不存在）
if not AUTH_DIR.exists():
    AUTH_DIR.mkdir(parents=True, exist_ok=True)

# 初始化auth.json（如果不存在）
if not AUTH_FILE_PATH.exists():
    with open(AUTH_FILE_PATH, 'w', encoding='utf-8') as f:
        json.dump({
            'token': '',
            'cookies': {}
        }, f, indent=2)


def save_auth_info(auth_info):
    """保存认证信息到auth.json文件"""
    try:
        # 读取现有数据（如果有）
        existing_data = {}
        if AUTH_FILE_PATH.exists():
            with open(AUTH_FILE_PATH, 'r', encoding='utf-8') as f:
                existing_data = json.load(f)
        
        # 合并新数据
        updated_data = {**existing_data, **auth_info}
        
        # 写入文件
        with open(AUTH_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(updated_data, f, indent=2)
        return True
    except Exception as e:
        print(f"保存认证信息失败: {e}")
        return False


def get_auth_info():
    """从auth.json文件获取认证信息"""
    try:
        if AUTH_FILE_PATH.exists():
            with open(AUTH_FILE_PATH, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {'token': '', 'cookies': {}}
    except Exception as e:
        print(f"获取认证信息失败: {e}")
        return {'token': '', 'cookies': {}} 